package com.bw.smartpark

import android.app.Application
import android.content.Context
import com.bw.common.utils.ImmersiveNightModeUtil
import com.bw.lib_base.base.BaseApp
import com.tencent.mmkv.MMKV
import com.therouter.TheRouter
import dagger.hilt.android.HiltAndroidApp
import me.jessyan.autosize.AutoSize
import me.jessyan.autosize.AutoSizeConfig
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMOptions;
import com.tencent.bugly.crashreport.CrashReport

@HiltAndroidApp
class App: BaseApp() {

    companion object {
        private var executorService: ExecutorService? = null

        fun getExecutorService(): ExecutorService {
            if (executorService == null || executorService!!.isShutdown) {
                executorService = Executors.newCachedThreadPool()
            }
            return executorService!!
        }
    }

    override fun onCreate() {
        super.onCreate()

        // 应用保存的夜间模式设置（防止闪屏）
        ImmersiveNightModeUtil.applySavedNightMode()

        // 屏幕适配
        AutoSize.initCompatMultiProcess(this)
        AutoSizeConfig.getInstance()
            .setBaseOnWidth(true)
            .setExcludeFontScale(true)

        MMKV.initialize(this)

        //环信
        val options:EMOptions  = EMOptions();
        options.setAppKey("1134241223154273#smartpark");
        // 其他 EMOptions 配置。
// context 为上下文，在 Application 或者 Activity 中可以用 this 代替
        EMClient.getInstance().init(context, options);

        //Bugly集成初始化
        CrashReport.initCrashReport(getApplicationContext());
        // 环信初始化
        try {
            val options = EMOptions()
            options.setAppKey("1134241223154273#smartpark")
            // 设置是否自动接受群组邀请
            options.setAutoAcceptGroupInvitation(false)
            // 设置是否需要已读回执
            options.setRequireAck(true)
            // 设置是否需要已送达回执
            options.setRequireDeliveryAck(true)

            EMClient.getInstance().init(this, options)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun attachBaseContext(base: Context?) {
        TheRouter.isDebug = true
        super.attachBaseContext(base)
    }

    override fun onTerminate() {
        super.onTerminate()
        // 关闭线程池
        executorService?.let { executor ->
            try {
                executor.shutdown()
                if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
                    executor.shutdownNow()
                    if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
                        // 强制关闭
                        executor.shutdownNow()
                    }
                }
            } catch (e: InterruptedException) {
                executor.shutdownNow()
                Thread.currentThread().interrupt()
            }
        }

        // 关闭环信客户端
        try {
            EMClient.getInstance().logout(true)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onLowMemory() {
        super.onLowMemory()
        // 内存不足时清理资源
        System.gc()
    }

    override fun onTrimMemory(level: Int) {
        super.onTrimMemory(level)
        // 系统建议释放内存时清理资源
        if (level >= android.content.ComponentCallbacks2.TRIM_MEMORY_MODERATE) {
            System.gc()
        }
    }
}